package immutable;

/**
 * 描述：演示栈封闭的两个例子，一个是基本类型的局部变量，一个是对象引用的局部变量
 * 先演示线程争抢带来错误结果，然后把变量放到方法内，情况就变了
 */

public class StackConfinement implements Runnable{
    int index = 0;

    public void inThread() {
        int neverGoOut = 0;
        for (int i = 0; i < 10000; i++) {
            neverGoOut++;
        }
        System.out.println("栈内的变量不会被其他线程访问到，所以不会出错" + neverGoOut);
    }
    @Override
    public void run() {
        for (int i = 0; i < 10000; i++) {
            index++;
        }
        inThread();
    }

    public static void main(String[] args) {
        StackConfinement sc = new StackConfinement();
        Thread t1 = new Thread(sc);
        Thread t2 = new Thread(sc);
        t1.start();
        t2.start();
        try {
            t1.join();
            t2.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(sc.index);
    }
}
